<template>
  <div v-loading="listLoading">

    <el-alert
      type="error"
      style="margin-bottom: 20px"
    >
      菜单属于系统配置，请在前后端协调下进行修改
    </el-alert>

    <div v-permission="['sys:menu:add']" style="margin-bottom: 20px">

      <el-input v-model="filterText" size="small" class="filter-item" style="width: 200px; margin-right: 10px" placeholder="搜索主菜单" />

      <el-button class="filter-item" size="small" type="primary" icon="el-icon-plus" @click="showDialog('0')">
        添加
      </el-button>

    </div>

    <el-table
      ref="table"
      :data="tableData"
      :default-expand-all.sync="defaultExpand"
      :filter-node-method="filterNode"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
      :header-cell-style="{'background':'#f2f3f4', 'color':'#555', 'font-weight':'bold', 'line-height':'32px'}"
      row-key="id"
      border
    >
      <el-table-column label="名称" prop="metaTitle" width="200px" />

      <el-table-column label="图标" width="80px" align="center">
        <template v-slot="scope">
          <svg-icon v-if="scope.row.metaIcon" :icon-class="scope.row.metaIcon" />
        </template>
      </el-table-column>

      <el-table-column label="类型" width="150px" align="center">
        <template v-slot="scope">
          {{ scope.row.menuType | menuTypeFilter }}
        </template>
      </el-table-column>

      <el-table-column label="显示" width="120px" align="center">
        <template v-slot="scope">
          <div v-if="scope.row.menuType !== 2">
            <span v-if="scope.row.hidden" style="color: #aaa">隐藏</span>
            <span v-else style="color: #0a84ff">显示</span>
          </div>

        </template>
      </el-table-column>

      <el-table-column label="菜单路由" prop="path" />
      <el-table-column label="菜单名称" prop="name" />
      <el-table-column label="权限标识" prop="permissionTag" width="200px" />

      <el-table-column align="center" label="排序" width="150px">
        <template v-slot="scope">
          <el-button v-permission="['sys:menu:sort']" title="下移" size="mini" icon="el-icon-sort-down" circle @click="handleSort(scope.row.id, 1)" />
          <el-button v-permission="['sys:menu:sort']" title="上移" size="mini" icon="el-icon-sort-up" circle @click="handleSort(scope.row.id, 0)" />
        </template>
      </el-table-column>

      <el-table-column align="center" label="操作" width="150px">
        <template v-slot="scope">
          <el-button v-permission="['sys:menu:add']" title="添加子菜单" size="mini" icon="el-icon-plus" circle @click="showDialog(scope.row.id)" />
          <el-button v-permission="['sys:menu:update']" title="编辑" size="mini" icon="el-icon-edit" circle @click="showDialog(scope.row.parentId, scope.row.id)" />
          <el-button v-permission="['sys:menu:delete']" title="删除" size="mini" icon="el-icon-delete" circle @click="handleDelete(scope.row.id)" />
        </template>
      </el-table-column>

    </el-table>


    <menu-update-dialog
      :visible.sync="dialogVisible"
      :current-id="currentId"
      :parent-id="parentId"
      @success="getList"
    />

  </div>
</template>

<script>

import { fetchTree, deleteData, sortData } from '@/api/sys/menu/menu'
import permission from '@/directive/permission'
import MenuUpdateDialog from '@/views/admin/sys/menu/components/MenuUpdateDialog/index.vue'

export default {
  name: 'SysMenu',
  components: { MenuUpdateDialog },
  directives: { permission },
  data() {
    return {
      filterText: '',
      iconDialog: false,
      defaultExpand: true,
      parentId: '',
      currentId: '',
      dialogVisible: false,
      tableData: [],
      backData: [],
      listLoading: true,
      listQuery: {
        current: 1,
        size: 10,
        params: {

        }
      }
    }
  },
  watch: {

    // 检测查询变化
    filterText: {
      handler(val) {
        // 还原备份数据
        if (this.backData.length>0) {
          this.tableData = this.backData
        }
        if (val) {
          // 备份数据
          this.backData = this.tableData
          this.tableData = this.searchData(val, this.tableData)
        }
      },
      deep: true
    }
  },
  created() {
    this.getList()
  },
  methods: {

    /**
     * 添加或修改
     * @param parentId
     * @param currentId
     */
    showDialog(parentId, currentId) {
      this.parentId = parentId
      this.currentId = currentId
      this.dialogVisible = true
    },

    getList() {
      this.listLoading = true
      fetchTree(this.listQuery.params).then(res => {
        this.tableData = res.data
        this.listLoading = false
      })
    },

    filterNode(value, data) {
      if (!value) return true
      return data.metaTitle.indexOf(value) !== -1
    },

    handleSort(id, sort) {
      sortData(id, sort).then(() => {
        this.$notify({
          title: '成功',
          message: '排序成功！',
          type: 'success',
          duration: 2000
        })
        this.getList()
      })
    },

    handleDelete(id) {
      // 删除
      this.$confirm('确实要删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const ids = []
        ids.push(id)

        deleteData(ids).then(() => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.getList()
        }).catch(err => {
          console.log(err)
        })
      })
    },

    /**
     * 前端搜索
     * @param value
     * @param arr
     * @returns {*[]}
     */
    searchData(value, arr) {
      if (!arr) {
        return []
      }
      const result = []
      arr.forEach(element => {
        // 搜索标题
        if (element.metaTitle.indexOf(value) > -1) {
          const ab = this.searchData(value, element.children)
          const obj = {
            ...element,
            children: ab
          }
          result.push(obj)
        } else {
          // 判断当前节点知否有子节点，并且子节点中有数据，有数据继续递归查找
          if (element.children && element.children.length > 0) {
            const ab = this.searchData(value, element.children)
            const obj = {
              ...element,
              children: ab
            }
            if (ab && ab.length > 0) {
              result.push(obj)
            }
          }
        }
      })
      return result
    }
  }
}
</script>
